import moment from 'moment';
import { useMemo } from 'react';
import CanvasCheckCalendar from '../CanvasCheckCalendar';
import './index.less';

type CheckCell = {
  dataStr: string; // 2022-1-1 格式
};

interface IProps {
  activeYear: number;
  dateRange: [moment.Moment, moment.Moment];
  checkList: CheckCell[];
  onSelect?: (i: string) => void;
  selected?: string;
  canvas?: boolean
}

const CheckCalendar = (props: IProps) => {
  const { checkList, dateRange, activeYear, onSelect, selected = '', canvas = true } = props;

  if (canvas) {
    return <CanvasCheckCalendar {...props} />
  }

  const [startDate, endDate] = dateRange;

  const displayConfig = useMemo(() => {
    if (!dateRange || !checkList) {
      return {
        cellConfig: [],
        monthLabel: [],
      };
    }
    let offset = 1;
    let calcDay = moment(startDate.toISOString());
    let startWeek = startDate.week();
    const monthLabelPosition: Record<string, number> = {}; // 月份标签标注的位置

    // 本年的前几天可能不属于本年的周计算，属于上年的52周，将其算为0周
    const startWeekFlag = startDate.isSame(
      moment(`${activeYear - 1}-12-31`),
      'week',
    );
    if (startWeekFlag) {
      startWeek = 0;
    }

    const list = []; // 每个单元的对应日期与排列位置
    while (calcDay.isSameOrBefore(endDate, 'day')) {
      const month = calcDay.month() + 1;
      const year = calcDay.year();
      if (year !== activeYear) {
        // 一个日历图最多显示一年的数据
        calcDay.add(offset, 'day');
        continue;
      }
      const day = calcDay.day();
      const date = calcDay.date();
      let week = calcDay.week();
      const copy = moment(calcDay.toISOString());

      let checked = false;

      const calcDayString = calcDay.format('YYYY-MM-DD');

      // week - startWeek即与最左侧一列相差的周数（横向列数偏移），额外补充计算周日的情形，同一周的周日在右侧一列第一个
      const sundayOffset = day === 0 ? 1 : 0;

      const weekFlag = calcDay.isSame(
        moment(`${activeYear - 1}-12-31`),
        'week',
      );
      if (weekFlag) {
        week = 0;
      }

      const monthOffset = week - startWeek + sundayOffset;

      if (date === 1) {
        monthLabelPosition[month] = monthOffset;
      }

      const checkRecord = checkList.find((i) => i.dataStr === calcDayString);
      if (checkRecord) {
        checked = true;
      }

      list.push({
        dayOffset: day,
        monthOffset,
        dateStr: calcDayString,
        moment: copy,
        divider: date === 1, // 用来标记月份的第一天单元，与上一个月份分割
        checked,
      });
      calcDay.add(offset, 'day');
    }
    return {
      cellConfig: list,
      monthLabel: monthLabelPosition,
    };
  }, [dateRange, checkList]);

  const renderMonthLabel = () => {
    const { monthLabel } = displayConfig;
    return Object.entries(monthLabel).map(([month, offset]) => (
      <label key={month} style={{ transform: `translateX(${offset * 20}px)` }}>
        {month}月
      </label>
    ));
  };

  const renderDayLabel = () => {
    return ['日', '一', '二', '三', '四', '五', '六'].map((i) => (
      <label key={i}>{i}</label>
    ));
  };

  const renderCells = () => {
    const { cellConfig } = displayConfig;
    return cellConfig.map((i) => (
      <div
        className={[
          'check-calendar__cell',
          i.checked ? 'check-calendar__cell--active' : '',
        ].join(' ')}
        key={i.dateStr}
        style={{
          transform: `translateY(${20 * i.dayOffset}px) translateX(${
            20 * i.monthOffset
          }px)`,
          borderTop: i.divider ? '4px solid #20ef2e' : 'none',
        }}
        data-date={i.moment.format('YYYY/MM/DD')}
        data-y={i.monthOffset}
        onClick={() => onSelect?.(i.dateStr)}
      ></div>
    ));
  };

  return (
    <div className="check-calendar__container">
      <div className="check-calendar__month">{renderMonthLabel()}</div>
      <div className="check-calendar__day">{renderDayLabel()}</div>
      <div className="check-calendar__cells">{renderCells()}</div>
    </div>
  );
};

export default CheckCalendar;
